package ca.usherbrooke.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;

public class XMLTools {

	static SAXBuilder sxb;
	static Document document;
	static Element racine;

	public XMLTools() {
	}

	public static void build(String filename) {
		try {
			sxb = new SAXBuilder();
			document = sxb.build(new File(filename));
			racine = document.getRootElement();
		} catch (JDOMException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void changeSource(String file, String newImageSource) {

		// get root child
		Element tilesetElement = racine.getChild("tileset");

		// set name
		tilesetElement.setAttribute("name", newImageSource);

		// set image source
		Element imageElement = tilesetElement.getChild("image");
		imageElement.setAttribute("source", "imgs/" + newImageSource);

		// save file
		try {
			enregistreFichier(file);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	static void enregistreFichier(String fichier) throws Exception {
		XMLOutputter sortie = new XMLOutputter(Format.getPrettyFormat());
		sortie.output(document, new FileOutputStream(fichier));
	}

	public static void main(String argvs[]) {
		XMLTools.build("scenario1.tmx");
		XMLTools.changeSource("scenario1.tmx", "TestImageName");
	}

}
